package com.yangguang.huahui.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings("deprecation")
public class CommonUtil {
    public static void myToastA(Context context, String str) {
        Toast toast=Toast.makeText(context, str, Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public static void myToastB(Context context, String str) {
        Toast toast=Toast.makeText(context, str, Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    public static String getDistance(double longitude1, double latitude1,
                                     double longitude2, double latitude2) {

        double distance = AMapUtils.calculateLineDistance(new LatLng(latitude1, longitude1), new LatLng(latitude2, longitude2));
        if (latitude1 == 0 || longitude1 == 0 || latitude2 == 0 || longitude2 == 0){
            return "定位失败";
        }else {
            return trans(distance);
        }
    }

    public static String getDistance(LatLng my_llatlng, double longitude2, double latitude2) {

        double distance = AMapUtils.calculateLineDistance(my_llatlng, new LatLng(latitude2, longitude2));
        return trans(distance);
    }

    private static String trans(double distance) {
        boolean isBig = false; // 是否为大于等于1000m
        if (distance >= 1000) {
            distance /= 1000;
            isBig = true;
        }
        return (new DecimalFormat("0.00").format(distance)) + (isBig ? "km" : "m");
    }
//
//    /**
//     * 把LatLng对象转化为LatLonPoint对象
//     */
//    public static LatLonPoint convertToLatLonPoint(LatLng latlon) {
//        return new LatLonPoint(latlon.latitude, latlon.longitude);
//    }
//
//    /**
//     * 把LatLonPoint对象转化为LatLon对象
//     */
//    public static LatLng convertToLatLng(LatLonPoint latLonPoint) {
//        return new LatLng(latLonPoint.getLatitude(), latLonPoint.getLongitude());
//    }

    /**
     * 中文转unicode
     *
     * @param str
     * @return 反回unicode编码
     */
    public String chinaToUnicode(String str) {
        String result = null;
        for (int i = 0; i < str.length(); i++) {
            int chr1 = (char) str.charAt(i);
            result += "\\u" + Integer.toHexString(chr1);
        }
        return result;
    }


    /**
     * unicode转中文
     *
     * @param str
     * @return
     */
    public static String unicodeToChinese(String str) {
        String s = "";
        for (char c : str.toCharArray())
            s += c;
        return s;
    }


    private static float density;

    /**
     * 检测sdcard是否可用
     *
     * @return true为可用，否则为不可用
     */
    public static boolean sdCardIsAvailable() {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED))
            return false;
        return true;
    }

    /**
     * Checks if there is enough Space on SDCard
     *
     * @param updateSize Size to Check
     * @return True if the Update will fit on SDCard, false if not enough space
     * on SDCard Will also return false, if the SDCard is not mounted as
     * read/write
     */
    public static boolean enoughSpaceOnSdCard(long updateSize) {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED))
            return false;
        return (updateSize < getRealSizeOnSdcard());
    }

    /**
     * get the space is left over on sdcard
     */
    @SuppressWarnings("deprecation")
    public static long getRealSizeOnSdcard() {
        File path = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath());
        StatFs statFs = new StatFs(path.getPath());
        long blockSize = statFs.getBlockSize();
        long availableBlocks = statFs.getAvailableBlocks();
        return availableBlocks * blockSize;
    }

    /**
     * Checks if there is enough Space on phone self
     */
    public static boolean enoughSpaceOnPhone(long updateSize) {
        return getRealSizeOnPhone() > updateSize;
    }

    /**
     * get the space is left over on phone self
     */
    @SuppressWarnings("deprecation")
    public static long getRealSizeOnPhone() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        long availableBlocks = stat.getAvailableBlocks();
        long realSize = blockSize * availableBlocks;
        return realSize;
    }

    /**
     * 根据手机分辨率从dp转成px
     *
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f) - 15;
    }

    /**
     * 是否为空值
     *
     * @param content
     * @return
     */
    public static boolean isNull(String content) {
        if (content == null) {
            return true;
        }
        if ("".equals(content) || "null".equalsIgnoreCase(content)) {
            return true;
        }
        return false;
    }

    //将指定日期转化为秒数
    public static long getMillisFromDate(String expireDate, String type) {
        if (expireDate == null || expireDate.trim().equals(""))
            return 0;
        SimpleDateFormat sdf = new SimpleDateFormat(type);
        Date date = null;
        try {
            date = sdf.parse(expireDate);
            return date.getTime() / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * @param time  时间
     * @param level 参考Calendar
     * @return "yyyy-MM-dd kk:mm:ss" 格式的时间
     */
    public static String longToTime(long time, int level) {
        if (time == 0){
            return "不限";
        }
        String format = "yyyy-MM-dd  kk:mm:ss";
        switch (level) {
            case Calendar.AM: {
                format = "yyyy-MM-dd kk:mm";
            }
            break;
            case Calendar.MINUTE: {
                format = "yyyy年MM月dd日 kk点mm";
            }
            break;
            case 1001: {
                format = "yyyy-MM-dd kk:mm";
            }
            break;
            case 1002: {
                format = "yyyy.MM";
            }
            break;
            case 1003: {
                format = "yyyy.MM.dd";
            }
            break;
            case 1004: {
                format = "yyyy年MM月dd日";
            }
            break;
            case 1005: {
                format = "kk:mm";
            }
            break;
            case Calendar.HOUR: {
                format = "yyyy-MM-dd kk";
            }
            break;
            case Calendar.DATE: {
                format = "yyyy-MM-dd";
            }
            break;
            case Calendar.MONTH: {
                format = "yyyy-MM";
            }
            break;
            case Calendar.YEAR: {
                format = "yyyy";
            }
            break;
            case  1006:{
                format = "MM-dd";
            }
                break;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(time);
    }

    /**
     * 格式化时间
     *
     * @param oldtime
     * @return
     */
    public static String formatTime(Context context, long oldtime,
                                    boolean showTime) {
        long newtime = System.currentTimeMillis() / 1000;
        long time = 0;
        if ((time = ((newtime - oldtime))) < 5) {
            return "刚刚";
        } else if ((time = ((newtime - oldtime))) < 60) {
            return time + "秒";
        } else if ((time = ((newtime - oldtime))) < 3600) {
            return time / 60 + "分";
        } else if ((time = ((newtime - oldtime))) < 3600 * 24) {
            return time / 3600 + "小时";
        } else if ((time = ((newtime - oldtime))) < 3600 * 24 * 30) {
            return time / (3600 * 24) + "天";
        } else {
            return "30" + "天";
        }
    }


    /**
     * 隐藏软键盘
     *
     * @param context
     * @param view
     */
    public static void hideInputMethod(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    //隐藏显示键盘
    public boolean hideSoftKeyboard(Activity activity) {
        if (activity.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (activity.getCurrentFocus() != null)
                ((InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
        return true;
    }

    /**
     * 判断本地是否安装了该包
     *
     * @param context
     * @param apkid
     * @param @return
     * @return boolean
     */
    public static boolean isClientInstalled(Context context, String apkid) {
        if (apkid != null) {
            String lowAppLabel = apkid.trim().toLowerCase();
            if (lowAppLabel.length() > 0) {
                PackageManager pm = context.getPackageManager();
                List<PackageInfo> packs = pm.getInstalledPackages(0);
                for (PackageInfo pack : packs) {
                    String appLabel = pack.applicationInfo.packageName
                            .toLowerCase();
                    if (appLabel.equals(lowAppLabel)) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 启动一个app
     */
    public static void startAPP(Context context, String appPackageName) {
        Intent queryIntent = new Intent("android.intent.action.MAIN");
        queryIntent.setComponent(new ComponentName(appPackageName,appPackageName + ".MsgCheck"));
        queryIntent.setAction("android.intent.action.VIEW");
        context.startActivity(queryIntent);
    }

    /**
     * 打开本地apk
     *
     * @param context
     * @param apkid   是否需要统计
     * @return void
     */
    public static void launchClient(Context context, String apkid) {
        if (apkid != null && apkid.length() > 0) {
            PackageManager pm = context.getPackageManager();
            Intent intent = pm.getLaunchIntentForPackage(apkid);
            if (intent != null) {
                context.startActivity(intent);
            }
        }
    }

    /**
     * 将文本设置到剪切板中
     *
     * @param context
     * @param str
     * @time 2011-6-27 下午02:53:41
     * @author:linyg
     */
    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    public static boolean setClipboard(Context context, String str) {
        try {
            ClipboardManager clip = (ClipboardManager) context
                    .getSystemService(Context.CLIPBOARD_SERVICE);
            clip.setText(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 从剪切板中读取文本
     *
     * @param context
     * @return
     * @time 2011-6-27 下午02:53:56
     * @author:linyg
     */
    @SuppressLint("NewApi")
    @SuppressWarnings("deprecation")
    public static String getClipboard(Context context) {
        ClipboardManager clip = (ClipboardManager) context
                .getSystemService(Context.CLIPBOARD_SERVICE);
        return clip.getText().toString();
    }

    /**
     * 将分享到新浪微博的配图，复制到Sdcard
     *
     * @return 配图在Sdcard的路径
     */
    public static String copyImgToSdcard(Context context) {
        File outFile = new File(new File(getSDPath()),
                "shengqian_weibo_share.jpg");
        if (!outFile.exists()) {

            InputStream in = null;
            OutputStream out = null;
            try {
                in = context.getAssets().open("shengqian_weibo_share.jpg");
                out = new FileOutputStream(outFile);

                byte[] buf = new byte[4 * 1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null)
                        in.close();
                    if (out != null)
                        out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return outFile.getAbsolutePath();
    }

    /**
    * 验证号码 手机号 固话均可
    *
    */
    public static boolean isPhoneNumberValid(String phoneNumber) {
        boolean isValid = false;
        CharSequence inputStr = phoneNumber;

        String expression = "((^(13|14|15|18|17|16|19)[0-9]{9}$)|(^[0]{1}[0-9]{2,3}-[0-9]{7,8}$)|(^[0]{1}[0-9]{2,3}[0-9]{7,8}$))";

        Matcher matcher = Pattern.compile(expression).matcher(inputStr);

        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }

    /**
     * 验证手机号
     * @param phone
     * @return
     */
    public static boolean isPhone(String phone){
        boolean isValid = false;
        CharSequence inputStr = phone;

        String expression = "(^(13|14|15|18|17|16|19)[0-9]{9}$)";

        Matcher matcher = Pattern.compile(expression).matcher(inputStr);

        if (matcher.matches()) {
            isValid = true;
        }
        return isValid;
    }

    /**
     * 获取sd卡路径
     *
     * @return
     */
    public static String getSDPath() {
        String sdDir = "";
        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED); // 判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory() + "/wuyou/";//获取跟目录
        } else {
            sdDir = "/data/data/com.workers.wuyou/wuyou/";
        }
        return sdDir;
    }

    /**
     * 将数据写入到sd卡中
     *
     * @param text 要保存的字符
     */
    public static void writeToSd(String filename, String text) {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            File sdCardDir = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);// 获取SDCard目录
            File sdFile = new File(sdCardDir, filename);
            try {
                FileOutputStream fos = new FileOutputStream(sdFile);
                fos.write(text.getBytes());
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * dip转px
     */
    public static int dipToPx(Context context, int dip) {
        if (density <= 0) {
            density = context.getResources().getDisplayMetrics().density;
        }
        return (int) (dip * density + 0.5f);
    }

    /**
     * px转dip
     */
    public static int pxToDip(Context context, int px) {
        if (density <= 0) {
            density = context.getResources().getDisplayMetrics().density;
        }
        return (int) ((px - 0.5f) / density);
    }

    /**
     * 手机IMEI号
     *
     * @param activity
     * @return
     */
    public static String getIMEI(Context activity) {
        TelephonyManager mTm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
        return mTm.getDeviceId();
    }

    /**
     * 获取IESI号
     *
     * @param activity
     * @return
     */
    public static String getIESI(Context activity) {
        TelephonyManager mTm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);

        return mTm.getSubscriberId();
    }

    /**
     * 手机型号
     *
     * @return
     */
    public static String getModel() {
        return Build.MODEL;
    }

    /**
     * 系统版本号
     *
     * @return
     */
    public static String getPhoneVersion() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 检查当前网络是否可用
     *
     * @param
     * @return
     */

    public static boolean isNetworkAvailable(Context activity) {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null) {
            return false;
        } else {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0) {
                for (int i = 0; i < networkInfo.length; i++) {
                    System.out.println(i + "===状态===" + networkInfo[i].getState());
                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 检测网络是否可用
     */

    public static boolean isNetWorkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable() && mNetworkInfo.isConnected();
            }
        }

        return false;
    }


    public static BitmapFactory.Options getBitmapOptions(String var0) {
        BitmapFactory.Options var1 = new BitmapFactory.Options();
        var1.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(var0, var1);
        return var1;
    }

    public static int calculateInSampleSize(BitmapFactory.Options var0, int var1, int var2) {
        int var3 = var0.outHeight;
        int var4 = var0.outWidth;
        int var5 = 1;
        if (var3 > var2 || var4 > var1) {
            int var6 = Math.round((float) var3 / (float) var2);
            int var7 = Math.round((float) var4 / (float) var1);
            var5 = var6 > var7 ? var6 : var7;
        }

        return var5;
    }

    public static int readPictureDegree(String var0) {
        short var1 = 0;

        try {
            ExifInterface var2 = new ExifInterface(var0);
            int var3 = var2.getAttributeInt("Orientation", 1);
            switch (var3) {
                case 3:
                    var1 = 180;
                case 4:
                case 5:
                case 7:
                default:
                    break;
                case 6:
                    var1 = 90;
                    break;
                case 8:
                    var1 = 270;
            }
        } catch (IOException var4) {
            var4.printStackTrace();
        }

        return var1;
    }

    public static Bitmap rotaingImageView(int var0, Bitmap var1) {
        Matrix var2 = new Matrix();
        var2.postRotate((float) var0);
        Bitmap var3 = Bitmap.createBitmap(var1, 0, 0, var1.getWidth(), var1.getHeight(), var2, true);
        return var3;
    }

    /**
     * 检测Sdcard是否存在
     *
     * @return
     */
    public static boolean isExitsSdcard() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
            return true;
        else
            return false;
    }

    public static List<Camera.Size> getResolutionList(Camera camera) {
        Camera.Parameters parameters = camera.getParameters();
        List<Camera.Size> previewSizes = parameters.getSupportedPreviewSizes();
        return previewSizes;
    }

    public static class ResolutionComparator implements Comparator<Camera.Size> {

        @Override
        public int compare(Camera.Size lhs, Camera.Size rhs) {
            if (lhs.height != rhs.height)
                return lhs.height - rhs.height;
            else
                return lhs.width - rhs.width;
        }

    }

    static String getString(Context context, int resId) {
        return context.getResources().getString(resId);
    }

    /**
     * 判断邮箱是否合法
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (null == email || "".equals(email)) return false;
        //Pattern p = Pattern.compile("\\w+@(\\w+.)+[a-z]{2,3}"); //简单匹配
        Pattern p = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");//复杂匹配
        Matcher m = p.matcher(email);
        return m.matches();
    }

    public static String getAreaName(String areaName){
        if (areaName.contains("省")){
            areaName = areaName.replace("省", "");
        } else if (areaName.contains("市")) {
            areaName = areaName.replace("市", "");
        }else if (areaName.contains("黎族苗族自治县")){
            areaName = areaName.replace("黎族苗族自治县", "");
        }else if (areaName.contains("黎族自治县")){
            areaName = areaName.replace("黎族自治县", "");
        } else if (areaName.contains("地区")){
            areaName = areaName.replace("地区", "");
        }else if (areaName.contains("布依族苗族自治州")){
            areaName = areaName.replace("布依族苗族自治州", "");
        }else if (areaName.contains("苗族侗族自治州")){
            areaName = areaName.replace("苗族侗族自治州", "");
        }else if (areaName.contains("哈尼族彝族自治州")){
            areaName = areaName.replace("哈尼族彝族自治州", "");
        }else if (areaName.contains("彝族自治州")){
            areaName = areaName.replace("彝族自治州", "");
        }else if (areaName.contains("壮族苗族自治州")){
            areaName = areaName.replace("壮族苗族自治州", "");
        }else if (areaName.contains("傣族自治州")){
            areaName = areaName.replace("傣族自治州", "");
        }else if (areaName.contains("白族自治州")){
            areaName = areaName.replace("白族自治州", "");
        }else if (areaName.contains("傣族景颇族自治州")){
            areaName = areaName.replace("傣族景颇族自治州", "");
        }else if (areaName.contains("傈傈族自治州")){
            areaName = areaName.replace("傈傈族自治州", "");
        }else if (areaName.contains("回族族自治州")){
            areaName = areaName.replace("回族族自治州", "");
        }else if (areaName.contains("蒙古族藏族自治州")){
            areaName = areaName.replace("蒙古族藏族自治州", "");
        }else if (areaName.contains("藏族自治州")){
            areaName = areaName.replace("藏族自治州", "");
        }else if (areaName.contains("蒙古自治州")){
            areaName = areaName.replace("蒙古自治州", "");
        }else if (areaName.contains("哈萨克自治州")){
            areaName = areaName.replace("哈萨克自治州", "");
        }else if (areaName.contains("特别行政区")){
            areaName = areaName.replace("特别行政区", "");
        }else if (areaName.contains("县")){
            areaName = areaName.replace("县", "");
        }
        return areaName;
    }
}
